﻿using AutoMapper;
using PagedList;
using SIG.DAL.Dapper.Model;
using SIG.DAL.Dapper.Repositories;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Helper;
using SIG.InputModel.Admin.Links;
using SIG.Resources.Admin;
using SIG.Service;
using SIG.ViewModel;
using SIG.ViewModel.Admin.Links;
using SIG.WebMVC.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class LinkCategoryController : BaseController
    {
        private readonly LinkCategoryRepository _categoryService;
        private readonly LinkRepository _linkRepository;
        private readonly PageMetaRepository _pageMetaService;
        private readonly IMapper _mapper;

        public LinkCategoryController( IMapper mapper)
        {
            _categoryService = new LinkCategoryRepository();
            _linkRepository = new LinkRepository();
            _pageMetaService = new PageMetaRepository();
            _mapper = mapper;

        }
        // GET: Admin/LinkCategory

        #region 分类

        public ActionResult Index(int? page, string keyword)
        {
            LinkCategoryListVM categoryListVM = GetElements(page, keyword);
            ViewBag.PageSizes = new SelectList(Site.PageSizes());
            return View(categoryListVM);
        }

        private LinkCategoryListVM GetElements(int? page, string keyword)
        {
            var vm = new LinkCategoryListVM();

            vm.Keyword = keyword;
            vm.PageIndex = page ?? 1;
            vm.PageSize = SettingsManager.Link.PageSize;
            int totalCount;
            var list = _categoryService.GetListPagedItems(vm.PageIndex, vm.PageSize, vm.Keyword, out totalCount);
          //  var specialistVMList = _mapper.Map<List<LinkCategory>, List<LinkCategoryVM>>(specialistlist);
            vm.TotalCount = totalCount;
            vm.Categories = new StaticPagedList<LinkCategory>(list, vm.PageIndex , vm.PageSize, vm.TotalCount); ;
            return vm;
        }

        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/LinkSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }

        [HttpGet]
        public ActionResult Add()
        {
            var vCategory = new LinkCategoryIM()
            {
                Active = true,
                Importance = 0
            };
            return PartialView("_Add", vCategory);
        }



        [HttpPost]
        public JsonResult Add(LinkCategoryIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            var newCategory = _mapper.Map<LinkCategoryIM, LinkCategory>(vm);
            newCategory.CreatedBy = Site.CurrentUserName;
            newCategory.CreatedDate = DateTime.Now;
            _categoryService.Create(newCategory);

            if (!string.IsNullOrEmpty(vm.Keywords) || !string.IsNullOrEmpty(vm.SEODescription))
            {
                var pageMeta = new PageMeta()
                {
                    ObjectId = newCategory.Id.ToString(),
                    Keyword = vm.Keywords.Replace('，', ','),
                    Description = vm.SEODescription,
                    ModelType = (int)ModelType.LINKCATEGORY
                };
                _pageMetaService.Create(pageMeta);
            }

            int count;
            var pageSize = SettingsManager.Link.PageSize;
            var list = _categoryService.GetListPagedItems(1, pageSize, string.Empty, out count);
           // List<LinkCategoryVM> categories = _mapper.Map<List<LinkCategory>, List<LinkCategoryVM>>(list);
            AR.Data = RenderPartialViewToString("_CategoryList", list);
      
            AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.LinkCategory));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpGet]
        public ActionResult Edit(int id)
        {

            LinkCategory category = _categoryService.GetById(id);
            if (category == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }

            var vm = _mapper.Map<LinkCategoryIM>(category);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.LINKCATEGORY, category.Id.ToString());
            if (pageMeta != null)
            {
                vm.Keywords = pageMeta.Keyword;
                vm.SEODescription = pageMeta.Description;
            }

            return PartialView("_Edit", vm);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]

        public JsonResult Edit(LinkCategoryIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            var newCategory = _categoryService.GetById(vm.Id);
            newCategory.Title = vm.Title;
            newCategory.Importance = vm.Importance;
            newCategory.Active = vm.Active;
            newCategory.UpdatedBy = Site.CurrentUserName;
            newCategory.UpdatedDate = DateTime.Now;
         //   var newCategory = _mapper.Map<LinkCategoryIM, LinkCategory>(vm);
            _categoryService.Update(newCategory);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.LINKCATEGORY, vm.Id.ToString());
            pageMeta = pageMeta ?? new PageMeta();


            if (!string.IsNullOrEmpty(vm.Keywords) || !string.IsNullOrEmpty(vm.SEODescription))
            {

                pageMeta.ObjectId = vm.Id.ToString();
                pageMeta.Keyword = vm.Keywords;
                pageMeta.Description = vm.SEODescription;
                pageMeta.ModelType = (int)ModelType.LINKCATEGORY;

                if (pageMeta.Id > 0)
                {
                    _pageMetaService.Update(pageMeta);
                }
                else
                {
                    _pageMetaService.Create(pageMeta);
                }
            }

           // var category = _mapper.Map<LinkCategoryVM>(newCategory);
            AR.Id = newCategory.Id;
            AR.Data = RenderPartialViewToString("_CategoryItem", newCategory);

            AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.LinkCategory));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        // DELETE: /User/DeleteSite
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            LinkCategory vCategory = _categoryService.GetById(id);
            var links = _linkRepository.GetCountByParentId(vCategory.Id);
            if (links>0)
            {
                AR.Setfailure(string.Format(Messages.HasChildCanNotDelete, EntityNames.LinkCategory, EntityNames.Link));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            _categoryService.Delete(vCategory);
            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.LinkCategory));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult IsActive(int id)
        {

            var vCategory = _categoryService.GetById(id);
            if (vCategory == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                vCategory.Active = !vCategory.Active;
                _categoryService.Update(vCategory);
                var vm = _mapper.Map<LinkCategoryVM>(vCategory);

                AR.Data = RenderPartialViewToString("_CategoryItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.LinkCategory));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }

        


        //[AllowAnonymous]
        //public JsonResult IsSeoNameUnique(string seoName, int? Id)
        //{
        //    return !IsExist(seoName, Id)
        //        ? Json(true, JsonRequestBehavior.AllowGet)
        //        : Json(false, JsonRequestBehavior.AllowGet);
        //}
        //[AllowAnonymous]
        //public bool IsExist(string seoName, int? id)
        //{
        //    var wType = _categoryService.GetAll().Where(w => w.SeoName == seoName);
        //    if (id > 0)
        //    {
        //        wType = wType.Where(w => w.Id != id);
        //    }

        //    if (wType.Count() > 0)
        //        return true;

        //    return false;
        //}



        #endregion
    }
}